const moment = require("moment");
const router = require("koa-router")();

/**
 * api {get} /home/finance 财务首页
 *
 * apiParam {Number} page 页码
 * apiParam {Number} type 类型
 *
 */
router.get("/finance", async (ctx, nex) => {
  const user = ctx.user;
  const data = ctx.query;
  const page = ctx.query.page < 0 ? 0 : parseInt(ctx.query.page);
  const type = data.type ? parseInt(data.type) : 0;
  // 分页查询消费记录
  const costLog = await BaaS.Models.cost_log
    .query(qb => {
      qb.where("user_id", "=", user.id);
      qb.orderBy("id", "desc");
      if (type) {
        qb.where("type", "=", type);
      }
    })
    .fetchPage({
      withRelated: ["user"],
      pageSize: ctx.config.pageSize,
      page: page,
      withRelated: []
    });
  // 查询充值金额列表
  const recharge = await BaaS.Models.recharge.query({}).fetchAll();
  Object.assign(costLog, { money: user.money });
  ctx.success({ costLog, recharge });
});
/**
 * api {post} /home/buy 添加trade
 *
 * apiParam {Number} recharge_price 充值金额
 * apiParam {String} type 支付类型
 *
 */
router.post("/tradeAdd", async (ctx, nex) => {
  const user = ctx.user;
  const { price, type } = ctx.post;
  if (price == 0) {
    ctx.error("请输入充值金额");
    return;
  } else {
    const notifyData = JSON.stringify({ user_id: user.id });
    const key = `user_id:${
      user.id
    }:money:${price}:payment:${type}:notifyData:${notifyData}`;
    const locked = await BaaS.redis.lock(key);
    if (locked) {
      const trade = await BaaS.Models.trade
        .forge({
          user_id: user.id,
          tradeid: moment().format("YYMMDDHHmmssS"),
          money: price,
          payment: type,
          notify_url: "/home/public/ump_pay_success",
          notify_data: notifyData
        })
        .save();
      // 新增消费记录
      BaaS.Models.cost_log
        .forge({
          user_id: user.id,
          orderid: trade.tradeid,
          money: price,
          type: 2,
          status: 0,
          remark: "账户充值"
        })
        .save();
      ctx.success(trade);
      await BaaS.redis.unlock(key);
    } else {
      console.log(`${key} Waiting`);
    }
  }
});
/**
 * api {get} /home/myCoupons 我的优惠券
 *
 */
router.get("/myCoupons", async (ctx, next) => {
  const user = ctx.user;
  const myCoupons = await BaaS.Models.user_coupon
    .query({ where: { user_id: user.id } })
    .fetch({ withRelated: ["coupon"] });
  ctx.success(myCoupons);
});

module.exports = router;
